<script>
import AMapLoader from "@amap/amap-jsapi-loader";

export default {
  name: "map-view",
  props: {
    address: String
  },
  emits: ["getAddr"],
  data() {
    return {
      map: null,
      markers: [],
      markersPosition: [],
      geoCoder: null,
      searchService: null, // 添加搜索服务
      searchText: '', // 添加搜索文本
      isSearchServiceReady: false, // 添加标志来指示 searchService 是否已经准备好
      isSearchResultVisible: false, // 添加标志来控制搜索结果面板的显示和隐藏
      drivingService: null, // 添加路径规划服务
      ridingService: null, // 骑行服务
      workService: null, // 步行服务
      startMarker: null, // 初始化 startMarker 为 null
      endMarker: null, // 终点标记
      isDrivingResultVisible: false, // 添加标志来控制导航结果容器的显示和隐藏
      isPopupVisible: false, // 添加标志来控制弹框的显示和隐藏
      selectedPoi: null, // 用于存储选中的搜索点信息
      activeName: 'Driving',
      startMarkerAddress: '', // 新增起点地址显示
      endMarkerAddress: '',   // 新增终点地址显示
      activeInputType: null   // 新增激活输入框类型标记
    };
  },
  mounted() {
    this.initAMap();
    this.$nextTick(() => { // 确保 DOM 已经渲染完成
      this.initPlaceSearch();
      this.initDrivingService(); // 初始化路径规划服务
    });
  },
  unmounted() {
    this.map?.destroy();
  },
  watch: {
    searchText(newVal) {
      if (newVal === '') {
        this.removeMarker();
        this.isSearchResultVisible = false; // 清空搜索框时隐藏搜索结果
      }
    }
  },
  methods: {
    initAMap() {
      window._AMapSecurityConfig = {
        securityJsCode: "9866258071c975621e9ec0237a30bebf",
      };

      let that = this;
      AMapLoader.load({
        key: '77652cd9a26359e9086df2e78d97571c',
        version: "2.0",
        plugins: ["AMap.Scale", "AMap.ToolBar", "AMap.Driving", "AMap.Transfer", "AMap.Riding", "AMap.Truck", "AMap.Walking"], // 移除 AMap.PlaceSearch 插件
      }).then(AMap => {
            that.map = new AMap.Map('container', {
              zoom: 11,
              center: [116.407394, 39.904211], // 默认中心点设为北京天安门
              viewMode: '3D'
            })
            AMap.plugin(["AMap.Scale", "AMap.ToolBar", 'AMap.Geolocation', "AMap.Geocoder"], function () {
              that.map.addControl(new AMap.Scale())
              let geolocation = new AMap.Geolocation({
                enableHighAccuracy: true,
                timeout: 10000,
                maximumAge: 0,
                convert: true,
                showButton: true,
                buttonPosition: 'LB', // 保持在左下角
                buttonOffset: new AMap.Pixel(10, 100), // 向上移动150像素，避免与ToolBar重叠
                showMarker: true,
                showCircle: true,
                panToLocation: true,
                zoomToAccuracy: true
              })
              that.map.addControl(geolocation)
              that.map.addControl(new AMap.ToolBar({
                showButton: true,
                position: 'RT', // 保持在左下角
                offset: [10, 100], // 向上移动150像素，避免与Geolocation重叠
              }))
              geolocation.getCurrentPosition((status, result) => {
                if (status === 'complete') {
                  that.markersPosition = [result.position.lng, result.position.lat];
                  that.map.setCenter([result.position.lng, result.position.lat]);
                  that.startMarker = { // 初始化 startMarker 为当前定位
                    lng: result.position.lng, lat: result.position.lat
                  };
                } else {
                  console.error('获取定位失败', result);
                  that.startMarker = {lng: 116.407394, lat: 39.904211}
                }
              })
              that.geoCoder = new AMap.Geocoder({
                radius: 200, //以已知坐标为中心点，radius为半径，返回范围内兴趣点和道路信息
                extensions: "base", //返回地址描述以及附近兴趣点和道路信息，默认“base”
                batch: false
              });
            });

            this.map.on('click', (e) => {
              this.addMarker(e)
            })
          }
      )
    },
    initPlaceSearch() { // 新增方法，用于初始化 PlaceSearch 服务
      AMapLoader.load({
        key: '77652cd9a26359e9086df2e78d97571c',
        version: "2.0",
        plugins: ["AMap.PlaceSearch"], // 仅加载 AMap.PlaceSearch 插件
      }).then(AMap => {
        this.searchService = new AMap.PlaceSearch({
          pageSize: 5, // 单页显示结果条数
          pageIndex: 1, // 页码
          city: "", // 兴趣点城市
          citylimit: false, // 是否强制限制在设置的城市内搜索
          map: this.map, // 展现结果的地图实例
          panel: "my-panel", // 结果列表将在此容器中进行展示
          autoFitView: true // 是否自动调整地图视野使绘制的 Marker 点都处于视口的可见范围
        });
        this.isSearchServiceReady = true; // 设置标志为已准备好
      });
    },
    initDrivingService() { // 初始化路径规划服务
      AMapLoader.load({
        key: '77652cd9a26359e9086df2e78d97571c',
        version: "2.0",
        plugins: ["AMap.Driving", "AMap.Transfer", "AMap.Walking", "AMap.Riding"] // 加载 AMap.Driving 插件
      }).then(AMap => {
        const drivingOptions = {
          policy: AMap.DrivingPolicy.LEAST_TIME, // 设置驾车策略为速度优先
          map: this.map,
          panel: "driving-panel"
        };
        this.drivingService = new AMap.Driving(drivingOptions);
        this.workService = new AMap.Walking({
          map: this.map,
          panel: "driving-panel"
        });
        this.ridingService = new AMap.Riding({
          map: this.map,
          panel: "driving-panel"
        });
      });
    },
    setActiveInput(type) {
      this.activeInputType = type
    },
    addMarker(e) {
      if (!this.activeInputType) return // 只处理激活状态下的点击
      //this.removeMarker()
      const {lng, lat} = e.lnglat
      if (this.activeInputType === 'start') {
        this.startMarkerAddress = `${lng},${lat}`;
        this.setStartMarker(lng, lat);
      } else {
        this.endMarkerAddress = `${lng},${lat}`;
        this.setEndMarker(lng, lat);
      }
      this.map.setFitView()
      //eslint-disable-next-line no-undef
      let marker = new AMap.Marker({
        map: this.map,
        position: [lng, lat],
        icon: require(`../../../../public/${this.activeInputType}.svg`), //添加 icon 图标 URL
        offset: [-10, -25],
      })
      this.activeInputType = null // 重置状态
      //marker.on("click", (e) => {
      //  this.$confirm('是否设置为起点或终点?', '提示', {
      //    confirmButtonText: '起点',
      //    cancelButtonText: '终点',
      //    type: 'warning'
      //  }).then(() => {
      //    this.setStartMarker(lng, lat);
      //  }).catch(() => {
      //    this.setEndMarker(lng, lat);
      //  });
      //});
      this.markers.push(marker)
      this.map.setFitView()
    },
    removeMarker() {
      if (this.markers) {
        this.map.remove(this.markers)
      }
    },
    setStartMarker(lng, lat) {
      this.startMarker = {lng, lat};
      //this.$emit("getAddr", {longitude: lng, latitude: lat, fulladdress: '起点'});
    },
    setEndMarker(lng, lat) {
      this.endMarker = {lng, lat};
      this.geoCoder.getAddress([lng, lat], (status, result) => {
        if (status === 'complete' && result.regeocode) {
          //curr.fulladdress = result.regeocode.formattedAddress;
          //curr.longitude = lng;
          //curr.latitude = lat;
          this.$emit("getAddr", {longitude: lng, latitude: lat, fulladdress: result.regeocode.formattedAddress});
        }
      });
    },
    searchMap() {
      if (this.isSearchServiceReady && this.searchText) {
        this.searchService.search(this.searchText, (status, result) => {
          if (status === 'complete' && result.info === 'OK') {
            //this.removeMarker();
            this.isSearchResultVisible = true;
            result.poiList.pois.forEach(poi => {
              //eslint-disable-next-line no-undef
              let marker = new AMap.Marker({
                map: this.map,
                position: [poi.location.lng, poi.location.lat],
                title: poi.name
              });
              //marker.on('click', (e) => {
              //  this.$confirm('是否设置为起点或终点?', '提示', {
              //    confirmButtonText: '起点',
              //    cancelButtonText: '终点',
              //    type: 'warning'
              //  }).then(() => {
              //    this.setStartMarker(poi.location.lng, poi.location.lat);
              //  }).catch(() => {
              //    this.setEndMarker(poi.location.lng, poi.location.lat);
              //  });
              //});
              this.markers.push(marker);
              this.map.setFitView();
            });
          } else {
            console.error('搜索失败', result);
          }
        });
      }
    },
    calculateRoute(way) {
      this.activeName = way
      let service = null
      this.isDrivingResultVisible = false
      this.drivingService.clear();
      this.ridingService.clear();
      this.workService.clear();
      if (way == 'Driving') {
        if (this.drivingService) {
          service = this.drivingService
        }
      } else if (way == 'Riding') {
        if (this.ridingService) {
          service = this.ridingService
        }
      } else if (way == 'Walking') {
        if (this.workService) {
          service = this.workService
        }
      }
      if (service && this.startMarker && this.endMarker) {
        this.isDrivingResultVisible = true
        this.$nextTick(() => {
          service.search([this.startMarker.lng, this.startMarker.lat], [this.endMarker.lng, this.endMarker.lat], (status, result) => {
            //eslint-disable-next-line no-empty
            if (status === 'complete') {
            } else {
              console.error('导航失败', result, status);
            }
          });
        })
      }
    },
    handleClick(tab, event) {
      if (this.endMarker) {
        if (tab.name === 'Driving') {
          this.calculateRoute('Driving');
        } else if (tab.name === 'Riding') {
          this.calculateRoute('Riding');
        } else if (tab.name === 'Walking') {
          this.calculateRoute('Walking');
        }
      }
    }
  }
}
</script>
<template>
  <div>
    <el-row>
      <el-col :span="7">
        <el-input v-model="searchText" placeholder="请输入搜索内容" style="width: 200px; margin-right: 10px;"/>
        <el-button type="primary" @click="searchMap">搜索</el-button>
      </el-col>
      <el-col :span="3">
        <el-button type="danger" @click="removeMarker">清空标点</el-button>
      </el-col>
      <el-col :span="2">
        <el-button type="info" v-if="startMarkerAddress&&endMarkerAddress"
                   @click="isDrivingResultVisible=!isDrivingResultVisible">
          {{ isDrivingResultVisible ? '折叠导航' : '展开导航' }}
        </el-button>
      </el-col>
      <el-col :span="12">
        <!-- 新增起点终点输入框 -->
        <el-form label-width="80px">
          <el-col :span="12">
            <el-form-item label="起点:">
              <el-input v-model="startMarkerAddress" @focus="setActiveInput('start')"
                        placeholder="点击输入框后在地图选择" style="width: 100%;"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="终点:">
              <el-input v-model="endMarkerAddress" @focus="setActiveInput('end')" placeholder="点击输入框后在地图选择"
                        style="width: 100%;"/>
            </el-form-item>
          </el-col>

        </el-form>
      </el-col>
    </el-row>


    <div id="container"></div>
    <div id="my-panel" v-show="isSearchResultVisible">
    </div>
    <el-tabs v-show="isDrivingResultVisible&&startMarkerAddress&&endMarkerAddress"
             style="position: absolute;top: 120px;right: 90px;width: 250px;"
             v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="驾车" name="Driving"></el-tab-pane>
      <el-tab-pane label="骑行" name="Riding"></el-tab-pane>
      <el-tab-pane label="步行" name="Walking"></el-tab-pane>
    </el-tabs>
    <div id="driving-panel" v-show="isDrivingResultVisible&&startMarkerAddress&&endMarkerAddress">
    </div>
  </div>
</template>
<style scoped lang="scss">
#container {
  padding: 0px;
  width: 100%;
  height: 600px;
  position: relative;
  margin: 10px 0 0 0;
}

#my-panel {
  position: absolute;
  top: 150px;
  right: 10px;
  z-index: 1000;
  width: 300px;
  background-color: white;
  padding: 10px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: 300px;
  overflow-y: auto;
}

#driving-panel {
  position: absolute;
  top: 160px;
  right: 25px;
  z-index: 1000;
  width: 300px;
  background-color: white;
  padding: 10px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: 300px;
  //overflow: hidden;
  overflow-y: auto;
}

.custom-content-marker {
  position: relative;
  width: 25px;
  height: 34px;
}

.custom-content-marker img {
  width: 100%;
  height: 100%;
}

.custom-content-marker .close-btn {
  position: absolute;
  top: -6px;
  right: -8px;
  width: 15px;
  height: 15px;
  font-size: 12px;
  background: #ccc;
  border-radius: 50%;
  color: #fff;
  text-align: center;
  line-height: 15px;
  box-shadow: -1px 1px 1px rgba(10, 10, 10, .2);
}

.custom-content-marker .close-btn:hover {
  background: #666;
}
</style>